from ast import main
import os
import sys
import traceback

import allure
from config.config import wf_api_server, wf_api_port, organization_id, x_api_key, BASE_DIR
import logging
from base.base_api import BaseApi
from util.file_util import update_sys_biz_date


class WfUploadApi(BaseApi):
    def __init__(self):
        base_url = f"http://{wf_api_server}:{wf_api_port}/compass-workflow-api"
        super().__init__(base_url)

    @allure.step("Upload file to queue: {queue_name}, file: {file_path}")
    def upload_file_to_queue(self, queue_name, file_path):
        logging.info(f"[START] Upload queue='{queue_name}', file='{os.path.basename(file_path)}'")
        
        try:
            endpoint = f"/{organization_id}/{queue_name}/in-resource/upload"
            with open(file_path, "rb") as file_data:
                files = {"file": file_data}
                headers = {"x-api-key": x_api_key}
                resp = self.post(endpoint, headers=headers, files=files)
            resp_json = resp.json()

            if resp.status_code == 200:
                file_id = resp_json.get("files", [{}])[0].get("fileId", None)
                logging.info(f"[SUCCESS] Uploaded queue='{queue_name}', fileId={file_id}, response: {resp_json}")
                return resp_json
            else:
                logging.info(f"[FAIL] Upload failed: queue='{queue_name}', status_code={resp.status_code}, response: {resp_json}")
                return None
        except Exception as e:
            logging.error(f"[ERROR] Full traceback: {traceback.format_exc()}")
            return None

    def trigger_ppa_daily_calculation(self, business_date, filepath=f'{BASE_DIR}/data/calculation/happy_case/ppa_daily.req', queue_name='ppa_daily'):
        update_sys_biz_date(business_date)
        return self.upload_file_to_queue(queue_name, filepath)

    def trigger_ppa_monthly_calculation(self, business_date, filepath=f'{BASE_DIR}/data/calculation/happy_case/ppa_monthly.req', queue_name='ppa_monthly'):
        update_sys_biz_date(business_date)
        return self.upload_file_to_queue(queue_name, filepath)

    def trigger_ppa_yearly_calculation(self, business_date, filepath=f'{BASE_DIR}/data/calculation/happy_case/ppa_daily.req', queue_name='ppa_yearly'):
        update_sys_biz_date(business_date)
        return self.upload_file_to_queue(queue_name, filepath)







































